package com.house365.updown.upload;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;

import com.house365.core.constant.CorePreferences;
import com.house365.updown.download.DFile;
import com.house365.updown.upload.HttpUploaderManager.OnServerResponse;
import com.house365.updown.upload.HttpUploaderManager.UploadListener;

/**
 * @author py
 * @date 2013-5-10
 * @comment
 */
public class Uploader {
	private Context context;

	
	private UploaderDBService dbService;

	private Map<String,UploadCompleteListener> onUploadCompleteListeners;;
	
	HttpUploaderManager httpUploaderManager ;
	public Uploader(Context context,OnServerResponse onServerResponse) {
		dbService = UploaderDBService.getDBService(context);
		httpUploaderManager = new HttpUploaderManager(context,onServerResponse);
		httpUploaderManager.setUploadListener(new UploadListener() {
				
			public void onError(long id,String response) {
				CorePreferences.DEBUG("httpUploaderManager.onError..");
				UFile uFile = dbService.getUFileByReferId(id);
				if (uFile != null) {
					//上传失败
					erroreuFile(uFile);
						if(onUploadCompleteListeners != null){
							UploadCompleteListener uploadCompleteListener = onUploadCompleteListeners.get(uFile.getOuterid());
							if(uploadCompleteListener!= null){
								uploadCompleteListener.onError(uFile,response);
								//执行完比以后，直接移除该方法
								onUploadCompleteListeners.remove(uFile.getOuterid());
							}
							
						}
				
				}
			}
			
			@Override
			public void onComplete(long id,String response) {
				CorePreferences.DEBUG("httpUploaderManager.onComplete..");
				UFile uFile = dbService.getUFileByReferId(id);
				if (uFile != null) {
					getUploadingStatus(uFile);
						// 上传成功了
						completeuFile(uFile);
						if(onUploadCompleteListeners != null){
							UploadCompleteListener uploadCompleteListener = onUploadCompleteListeners.get(uFile.getOuterid());
							if(uploadCompleteListener!= null){
								uploadCompleteListener.onComplete(uFile,response);
								//执行完比以后，直接移除该方法
								onUploadCompleteListeners.remove(uFile.getOuterid());
							}
							
						}
				
				}
			}
		});
		//因为发送图片、语音等，是先上传，后发送IM消息，所以，如果上次异常退出后，直接将没上传的消息清除掉，下次用户手动点击，再次发送
		dbService.clearUndone();
//		UFile dfile = dbService.getUploadingUFile();
//		if (dfile != null) {
//			// 有正在下载,将状态置为等待
//			dbService.moveUploadingToQueue(dfile);
//		}
//		startNewUploadFile();
	}

	

	public void destory() {
		UFile dfile = dbService.getUploadingUFile();
		if (dfile != null) {
			// 有正在下载,将状态置为等待
			dbService.moveUploadingToQueue(dfile);
		}
	}
	
	/**
	 * 添加一个下载任务
	 * @param uFile
	 */
	public void addUFile(UFile uFile) {
		CorePreferences.DEBUG("addUFile..");
		dbService.saveUFile(uFile, UPLOAD_STAUTS_QUEUE);
		startNewUploadFile();
	}

	/**
	public void setPriority(String id, int priority) {
		UFile uFile = getUFileQueueByOuterId(id);
		uFile.setPriority(priority);
		Collections.sort(uFilesQueue, new Comparator<UFile>() {
			@Override
			public int compare(UFile object1, UFile object2) {
				return object1.getPriority() - object2.getPriority();
			}
		});
	}

	public void increasePriority(String id) {
		UFile uFile = getUFileQueueByOuterId(id);
		int i = uFile.getPriority() + 1;
		if (i > 10) {
			i = 10;
		}
		uFile.setPriority(i);
		Collections.sort(uFilesQueue, new Comparator<UFile>() {
			@Override
			public int compare(UFile object1, UFile object2) {
				return object1.getPriority() - object2.getPriority();
			}
		});
	}

	public void decreasePriority(String id) {
		UFile uFile = getUFileQueueByOuterId(id);
		int i = uFile.getPriority() - 1;
		if (i < 1) {
			i = 1;
		}
		uFile.setPriority(i);
		Collections.sort(uFilesQueue, new Comparator<UFile>() {
			@Override
			public int compare(UFile object1, UFile object2) {
				return object1.getPriority() - object2.getPriority();
			}
		});
	}
	*/

	private void startNewUploadFile() {
		synchronized (this) {
			CorePreferences.DEBUG("startNewUploadFile..");
		UFile uFile = dbService.getUploadingUFile();
		if (uFile  == null) {
			UFile toDownUFile = dbService.getFirstQueueUFile();
			if(toDownUFile!= null){
				long id = uploadFile(toDownUFile);
				toDownUFile.setReferId(id);
				dbService.moveQueueToUploading(toDownUFile);
			}
			
		}
		}
	}

	private long uploadFile(UFile uFile) {
		synchronized (this) {
			//启动一个下载任务
			CorePreferences.DEBUG("uploadFile..");
			return httpUploaderManager.uploadFile(uFile);
		}
	}

	public void getUploadingStatus(UFile uFile) {
		synchronized (this) {
			UploaderInfo downInfo =  httpUploaderManager.getUploaderInfo(uFile.getReferId());
			if(downInfo != null){
				uFile.setUploadSize(downInfo.getNowSize());
				uFile.setStatus(downInfo.getStatus());
				if (uFile.getTotalSize() <= 0) {
					// 查询下载文件总大小
					long totalSize =downInfo.getMaxSize();
					if(totalSize>0){
						uFile.setTotalSize(totalSize);	
					}
					
					dbService.updateUploadingInfo(uFile);
				}
			}
		

		}
	}

	public void removeFileByOuterId(String outerid) {
		synchronized (this) {
			UFile uFile = dbService.getUFileByOuterId(outerid);
			if(uFile!= null){
				if (uFile.getType() == UPLOAD_STAUTS_UPLOADING) {
					//如果正在下载，移动到待下载区
					dbService.moveUploadingToQueue(uFile);
					httpUploaderManager.cancelUpload(uFile.getReferId());
					startNewUploadFile();
				}else if(uFile.getType() == UPLOAD_STAUTS_QUEUE){
					//直接移除
					dbService.removeUFileOuterId(uFile.getOuterid());
				}
					
			}
			

		}
	}
	public UFile getUploadingUFile() {
		return dbService.getUploadingUFile();
	}

	public void completeuFile(UFile uFile) {
		synchronized (this) {
			//上传成功了
			dbService.moveUploadingToUploaded(uFile);
			// 添加下一个下载任务
			startNewUploadFile();
		}
	}
	public void erroreuFile(UFile uFile) {
		synchronized (this) {
			// 上传失败,移除到待下载区域
			dbService.moveUploadingToQueue(uFile);
			// 添加下一个上传任务
			startNewUploadFile();
		}
	}
	// public int getCount() {
	// return uFiles == null ? 0 : uFiles.size();
	// }

	public static final int UPLOAD_STAUTS_QUEUE = 1;
	public static final int UPLOAD_STAUTS_UPLOADING = 2;
	public static final int UPLOAD_STAUTS_UPLOADED = 3;
	public static final int UPLOAD_STAUTS_UNKONW = -1;

	


	public int getStatusByOuterId(String outerid) {
		UFile uFile = dbService.getUFileByOuterId(outerid);
		if(uFile != null){
			return uFile.getType();
		}else{
			return UPLOAD_STAUTS_UNKONW;
		}
	}
	public UFile getUFileByOuterId(String outerid){
		return dbService.getUFileByOuterId(outerid);
	}
	public boolean isUploading(){
		if(getUploadingUFile()!= null){
			return true;
		}
		return false;
	}
	public void addUploadCompleteListener(String key,UploadCompleteListener listener){
		if(onUploadCompleteListeners == null){
			onUploadCompleteListeners = new HashMap<String,UploadCompleteListener>();
		}
		onUploadCompleteListeners.put(key,listener);
	}
	public interface UploadCompleteListener{
		public void onComplete(UFile uFile,String httpResponse);
		public void onError(UFile uFile,String httpResponse);
	}
	
}
